package Project4;

import java.util.*;

class IfStatement extends Statement{
	private ArrayList<Statement> trueStatements = new ArrayList<Statement>();
	private ArrayList<Statement> falseStatements = new ArrayList<Statement>();
	private int labelCounter = 0;
	public boolean optimizedTrue = false;
	public boolean optimizedFalse = false;
	public BooleanStatement booleanStatement;

	public IfStatement(int labelCounter){
		this.labelCounter = labelCounter;
	}

	public void addIf(ArrayList<Statement> t){
		trueStatements = t;
	} 

	public void addElse(ArrayList<Statement> e){
		falseStatements = e;
	}

	public void addBoolean(BooleanStatement bs){
		booleanStatement = bs;
	}

	public String toString(){
		String r = "";
		String b = buildBranchCondition();
		
		if(optimizedTrue){
			r += "#optimized if (always true)\n";
			for(Statement s: trueStatements){
				r += s + "\n";
			}
			return r;
		} else if (optimizedFalse){
			r += "#optimized if (always false)\n";
			for(Statement s: falseStatements){
				r += s + "\n";
			}
			return r;
		}


		r += "//if statement \n";
		r += b + " ELSE_STMT_" + labelCounter + "\n";
		for(Statement s: trueStatements){
			r += s + "\n";
		}
		r += "j IF_END_" + labelCounter + "\n";
		r += "ELSE_STMT_" + labelCounter + ":\n";
		for(Statement s: falseStatements){
			r += s + "\n";
		}
		r += "IF_END_" + labelCounter + ":\n";

		return r;
	}

	private String buildBranchCondition(){
		if(booleanStatement == null){
			return "";
		}
		String b = "";
		b += "li $s6, " + booleanStatement.getFirstExpression().getValue() + "\n";
		b += "li $s7, " + booleanStatement.getSecondExpression().getValue() + "\n";
		b += booleanStatement.getConditional() + "$s6, $s7 ";
		return b;
	}
}
